package top.malegod.controller;

import com.alipay.api.AlipayApiException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.malegod.model.Alipay;
import top.malegod.service.AlipayService;
import top.malegod.utils.AlipayConfig;

/**
 * Create by IntelliJ IDEA
 *
 * @author: AbelEthan
 * @date-Time: 2018/5/23 14:30
 * @description: 支付宝基本功能
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    /**
     * 交易关闭
     *
     * @param outTradeNo
     * @param tradeNo
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/close.do", method = RequestMethod.POST)
    public void close(
            @RequestParam(value = "WIDout_trade_no") String outTradeNo,
            @RequestParam(value = "WIDtrade_no") String tradeNo)
            throws AlipayApiException {
        if (outTradeNo != null || tradeNo != null) {
            String s = alipayService.close(outTradeNo, tradeNo);
        }

    }

    /**
     * 查询对账单下载地址
     *
     * @param billType
     * @param billDate
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/downloadUrl.do", method = RequestMethod.POST)
    public void downloadUrl(
            @RequestParam(value = "WIDbill_type") String billType,
            @RequestParam(value = "WIDbill_date") String billDate)
            throws AlipayApiException {
        if (billType != null && billDate != null) {

            String s = alipayService.downloadUrl(billType, billDate);

        }
    }

    /**
     * 支付
     *
     * @param alipay
     * @param response
     * @throws IOException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/pay.do", method = RequestMethod.POST)
    @ResponseBody
    public void pay(Alipay alipay, HttpServletResponse response) throws IOException, AlipayApiException {

        if (alipay.getWIDout_trade_no() != null) {
            // 超时时间 可空
            alipay.setTimeOutEcpress("2m");
            // 销售产品码 必填
            alipay.setProductCode("QUICK_WAP_WAY");

            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式

            String form = alipayService.pay(alipay);

            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    /**
     * 线下交易查询
     *
     * @param outTradeNo
     * @param tradeNo
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/query.do", method = RequestMethod.POST)
    public void query(
            @RequestParam(value = "WIDout_trade_no") String outTradeNo,
            @RequestParam(value = "WIDtrade_no") String tradeNo)
            throws AlipayApiException {
        if (outTradeNo != null || tradeNo != null) {
            String s = alipayService.query(outTradeNo, tradeNo);
        }
    }


    /**
     * 交易退款
     *
     * @param alipay
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/refund.do", method = RequestMethod.POST)
    public void refund(Alipay alipay)
            throws AlipayApiException {
        if (alipay.getWIDout_trade_no() != null
                || alipay.getWIDtrade_no() != null) {

            String s = alipayService.refund(alipay);

        }
    }

    /**
     * 统一收单交易退款查询
     *
     * @param alipay
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/refundQuery.do", method = RequestMethod.POST)
    public void refundQuery(Alipay alipay)
            throws AlipayApiException {
        if (alipay.getWIDout_trade_no() != null
                || alipay.getWIDtrade_no() != null
                && alipay.getWIDout_request_no() != null) {

            String s = alipayService.refundQuery(alipay);

        }
    }

    /**
     * 获取支付宝GET过来反馈信息
     *
     * @param request
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/return_url.do")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException, ServletException {

        Map<String, String> params = getParams(request);
        alipayService.returnUrl(params);

        return "alipayNice";
    }

    /**
     * 获取支付宝POST过来反馈信息
     *
     * @param request
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping("/notify_url.do")
    public String notifyUrl(
            @RequestParam(value = "trade_status") String tradeStatus, HttpServletRequest request)
            throws AlipayApiException, UnsupportedEncodingException {
        //
        Map<String, String> params = getParams(request);
        alipayService.notifyUrl(params, tradeStatus);
        return "mobile/orderInfo";
    }

    private Map<String, String> getParams(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<>(16);
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
           /*valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");*/
            params.put(name, valueStr);
        }
        return params;
    }

}
